import {
  Button,
  Empty,
  Input,
  NavBar,
  Toast,
  Image as MyImage,
} from "antd-mobile";
import { SearchOutline } from "antd-mobile-icons";
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import $fetch from "../../../utils/app/$fetch";
import $reducer from "../../../utils/app/$reducer";
import Decimal from "decimal.js";
import "./style.scss";

const GoodsListPage = () => {
  const navigate: any = useNavigate();
  // const [goodsList, setGoodsList] = useState([]);
  const initState = {
    isLoading: true,
    goodsList: [],
    goodsListLeft: [],
    goodsListRight: [],
    fetchData: [],
    totalAmount: 0,
    totalNum: 0,
    cartList: [],
    searchKey: "",
  };

  const [state, dispatch] = $reducer({ ...initState });

  // 获取商城列表
  useEffect(() => {
    queryGoodsList();
    queryCartList();
  }, []);

  useEffect(() => {
    if (state?.goodsList?.length > 0) {
      state?.goodsList.forEach((item: any) => {
        const img: any = new Image();
        img.src = item?.goodsPhoto;
      });
    }
  }, [state?.goodsList]);

  const queryGoodsList = async () => {
    const goodsRes: any = await $fetch("goods/goodsInf");
    let left: any = [];
    let right: any = [];
    goodsRes?.map((item: any, index: any) => {
      if (index % 2 === 0) {
        left.push(item);
      } else {
        right.push(item);
      }
    });
    dispatch({
      goodsListLeft: left,
      goodsListRight: right,
      goodsList: goodsRes,
      fetchData: goodsRes,
      isLoading: false,
    });
  };

  const queryCartList = async () => {
    const cartRes: any = await $fetch("cart/list", {}, { loading: false });
    dispatch({ cartList: cartRes });
    handleTotalAmount(cartRes);
  };

  const handleTotalAmount = (goods: any) => {
    if (goods?.length > 0) {
      let totalAmount: any = 0;
      goods?.forEach((item: any) => {
        const price = new Decimal(item?.price);
        const quantity = new Decimal(item.quantity);
        const temp = price.mul(quantity);
        totalAmount = temp.add(totalAmount).toFixed(2);
        totalAmount = totalAmount.toString();
        console.log(totalAmount, "____totalAmount");

        // totalAmount += Number(item?.price) * item.quantity;
      });
      dispatch({ totalAmount, totalNum: goods?.length });
    }
  };

  const handleAddCart = async (item: any) => {
    await $fetch(
      "cart/add",
      {
        ...item,
        goodsPhoto: item?.goodsThumbnail,
        quantity: 1,
        price: item?.goodsPrice,
      },
      { method: "post", loading: false }
    );
    Toast.show({ content: "加入购物车成功", duration: 500 });
    await queryCartList();
  };

  const handleInput = (value: any) => {
    dispatch({ searchKey: value });
  };

  const handleSearch = () => {
    if (state?.searchKey) {
      const newGoodsList = state?.fetchData.filter((item: any) =>
        item?.goodsName.includes(state?.searchKey)
      );
      let left: any = [];
      let right: any = [];
      newGoodsList?.map((item: any, index: any) => {
        if (index % 2 === 0) {
          left.push(item);
        } else {
          right.push(item);
        }
      });
      dispatch({
        goodsListLeft: left,
        goodsListRight: right,
      });
      return;
    }
    queryGoodsList();
  };

  const back = () => {
    window.history.go(-1);
  };

  const renderView = () => {
    if (state?.isLoading) return null;
    if (!state?.goodsList?.length) return <Empty description="暂无商品" />;
    return (
      <ul className="that_goods_wraper">
        <div>
          {state?.goodsListLeft?.map((item: any) => {
            return (
              <li
                onClick={() => {
                  navigate(`/goods/detail`, {
                    state: { goodsId: item?.goodsId },
                  });
                }}
                key={item?.goodsId}
              >
                <MyImage
                  src={item?.goodsPhoto}
                  width="100%"
                  height="100%"
                  // height="1.6rem"
                  lazy={true}
                  fit="cover"
                  placeholder={<MyImage src="" width="100%" height="1.6rem" />}
                />
                <div className="detail_wraper">
                  <h3>{item?.goodsName}</h3>
                  <div className="item_footer">
                    <div className="price">
                      <span>￥</span>
                      <span>{item?.goodsPrice}</span>
                    </div>
                    <i
                      onClick={(e: any) => {
                        e.stopPropagation(); // 阻止事件冒泡
                        handleAddCart(item);
                      }}
                      className="iconfont"
                    >
                      &#xe81f;
                    </i>
                  </div>
                </div>
              </li>
            );
          })}
        </div>
        <div>
          {state?.goodsListRight?.map((item: any) => {
            return (
              <li
                onClick={() => {
                  navigate(`/goods/detail`, {
                    state: { goodsId: item?.goodsId },
                  });
                }}
                key={item?.goodsId}
              >
                <MyImage
                  src={item?.goodsPhoto}
                  width="100%"
                  height="100%"
                  lazy={true}
                  fit="cover"
                  placeholder={<MyImage src="" width="100%" height="1.6rem" />}
                />
                <div className="detail_wraper">
                  <h3>{item?.goodsName}</h3>
                  <div className="item_footer">
                    <div className="price">
                      <span>￥</span>
                      <span>{item?.goodsPrice}</span>
                    </div>
                    <i
                      onClick={(e: any) => {
                        e.stopPropagation(); // 阻止事件冒泡
                        handleAddCart(item);
                      }}
                      className="iconfont"
                    >
                      &#xe81f;
                    </i>
                  </div>
                </div>
              </li>
            );
          })}
        </div>
      </ul>
    );
  };

  return (
    <div className="container_goods_list">
      <NavBar
        style={{
          "--border-bottom": "1px #eee solid",
        }}
        onBack={back}
      >
        官方商城
      </NavBar>
      <div className="shop_content">
        <div className="that_search">
          <div className="item_input">
            <SearchOutline />
            <Input
              placeholder="请输入关键词检索"
              clearable
              onChange={(value) => handleInput(value)}
            />
            <div onClick={handleSearch}>搜索</div>
          </div>
        </div>
        {renderView()}
      </div>

      <div className="that_footer">
        <div className="item_left">
          <div>
            <i
              className="iconfont"
              onClick={() => {
                navigate("/goods/cart");
              }}
            >
              &#xe63b;
            </i>
            {state?.totalNum > 0 && (
              <span className="num">{state?.totalNum}</span>
            )}
          </div>
          <span className="total">￥{state?.totalAmount}</span>
        </div>
        {/* <div className="item_button"> */}
        <Button
          onClick={() => {
            if (state?.totalAmount === 0) return;
            const cartIds = state?.cartList.map((item: any) => item?.id);
            navigate("/goods/order", {
              state: { cartIds },
            });
          }}
        >
          结算
        </Button>
        {/* </div> */}
      </div>
    </div>
  );
};
export default GoodsListPage;
